package org.NooLab.itexx.app.config;

import java.awt.Dimension;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import javax.swing.JFrame;

import org.NooLab.itexx.app.gui.definition.ITexxWindowGui2;
import org.NooLab.itexx.app.gui.definition.ITexxWindowGuiIntf;
import org.NooLab.itexx.app.up.ITexxWindowStartup;
import org.NooLab.utilities.files.DFutils;
import org.NooLab.utilities.files.PathFinder;

import org.NooLab.utilities.gui.SystemProperties;
import org.NooLab.utilities.logging.LogControl;
import org.NooLab.utilities.strings.StringsUtil;

public class AttendingAppProperties {

	private ITexxWindowGuiIntf windowGui;

	private boolean isFirstStart=false;

	private String appBasePath;
	private ITexxAppPropertiesIntf appProperties;
	private String rawXStartupPropsfilename;

	int appLogControl = 1;
	String appLogOutFile ="";

	
	Properties windowProps = new Properties();
	DFutils fileutl = new DFutils();
	// ========================================================================
	public AttendingAppProperties() throws Exception{
		
		prepare();
	}
	// ========================================================================

	public ITexxAppPropertiesIntf get() {
		// 
		return appProperties;
	}
	
	private void prepare() throws Exception{
	
		// detecting "first start" after installation
		String binPath = (new PathFinder()).getAppBinPath(this.getClass(), true) ;
		
    	// seedling startup info (such as last session id, last user, whether to load last session...
		ITexxWindowStartup.setApplicationID("noolabmuse", this.getClass());
		
		// read properties from file, if such exists... if not, it creates one with defaults
		appBasePath = ITexxWindowStartup.getProjectBasePath(); 
		System.out.println("application is running on base path : "+appBasePath) ;
		
		appProperties = ITexxAppProperties.getInstance( appBasePath ); 
		
		System.out.println("application is running on configuration : "+appProperties.getConfigFilename()+"\n") ;
		
		appProperties.save();
		
		rawXStartupPropsfilename = DFutils.createPath( binPath ,"application.position");
		
		if (DFutils.fileExists(rawXStartupPropsfilename)==false){
			
			isFirstStart = true;
			
			setDefaultWindowProperties();
			
			appLogControl = 2;
			appLogOutFile = DFutils.createPath( binPath ,"firstStart.log");
			
			windowProps.put("LogControl","2");
			windowProps.put("LogOutFile",""+appLogOutFile);
			
		}else{
			appLogOutFile = DFutils.createPath( binPath ,"console.log");
			
			
			windowProps.load(new FileInputStream(rawXStartupPropsfilename));
			
			if (windowProps.containsKey("LogControl")){
				int llev = 1;
				String ls = windowProps.getProperty("LogControl") ;
				if (ls!=null){
					if (StringsUtil.isNumeric(ls)){
						llev = Integer.parseInt(ls);
					}
				}
				LogControl.Level = llev;
			}
			
			if (windowProps.get("x")==null){
				setDefaultWindowProperties();
			}
			checkMac();
		}

	}


	private void checkMac() {
		// 
		String systemMacStr = SystemProperties.macAddress() ;
		
		String propsMac = "";
		
		if (windowProps.containsKey("mac")){
			propsMac = windowProps.getProperty("mac");
		}
		
		if (propsMac.contentEquals(systemMacStr)==false){
			isFirstStart=true;
			
		}
	}
	
	
	private void setDefaultWindowProperties() throws FileNotFoundException, IOException {
		// 
		windowProps.put("x", ""+(int)getDefaultX());
		windowProps.put("y", ""+(int)getDefaultY());
		windowProps.put("w", ""+(int)getDefaultW());
		windowProps.put("h", ""+(int)getDefaultH());
		windowProps.put("style", "simple"); // simple window
	
		windowProps.store(new FileOutputStream(rawXStartupPropsfilename), null);

	}
	
	public void storeWindowProperties( int x, int y, int w, int h, String style) throws FileNotFoundException, IOException{
		windowProps.put("x", ""+x);
		windowProps.put("y", ""+y);
		windowProps.put("w", ""+w);
		windowProps.put("h", ""+h);
		
		if (style.toLowerCase().startsWith("s")){
			style="simple" ;
		}else{
			style="full" ;
		}
		windowProps.put("style", style);

		if (windowGui.isStatusBarHidden()){
			windowProps.put("statusbar", "0");	
		}else{
			windowProps.put("statusbar", "1");
		}
		
		int ph=0;
		ph = windowGui.getResultPanelSize();
		windowProps.put("panels.height",""+ph);
		
		String nicmac = SystemProperties.macAddress() ;
		windowProps.put("mac", nicmac);
		
		windowProps.put("LogControl",""+LogControl.Level);
		windowProps.put("LogOutFile",""+appLogOutFile);

		windowProps.store(new FileOutputStream(rawXStartupPropsfilename), null);
	}
	
	public void storeWindowProperties(ITexxWindowGuiIntf gui) throws FileNotFoundException, IOException {
		// 
		windowGui = gui;
		if (gui != null){
			JFrame frame = gui.getMainFrame() ;
			
			int x = frame.getLocation().x;
			int y = frame.getLocation().y;
			int w = frame.getSize().width;
			int h = frame.getSize().height;
			String style = "simple";
			if (gui.isSimpleWindow()){
				style = "simple";
			}else{
				style = "full" ;
			}
			
			storeWindowProperties( x, y, w, h, style) ;
		}
		
	}

	public void restoreLastWindowState(ITexxWindowGuiIntf gui) {
		
		JFrame frame ;
		this.windowGui = gui ;
		frame = windowGui.getMainFrame() ;
		
		int x=800,y=100, w=350,h=500 ;
		
		String xs = (String) windowProps.get("x");
		String ys = (String) windowProps.get("y") ;
		
		if (xs!=null){
			x = Integer.parseInt(xs);
		}
		if (ys!=null){
			y = Integer.parseInt(ys);
		}
		
		frame.setLocation(x,y);

		String ws = (String) windowProps.get("w");
		String hs = (String) windowProps.get("h") ;
		
		if (ws!=null){
			w = Integer.parseInt(ws);
		}
		if (hs!=null){
			h = Integer.parseInt(hs);
		}

		frame.setSize( w,h );
		
		// check the vertical size: is there enough space to the lower border of the screen
		
		windowGui.controlVerticalSize();
		
		String phs = (String) windowProps.get("panels.height");
		int ph=0;
		if (phs!=null){
			ph = Integer.parseInt(phs);
		}
		if (ph<=1){
			ph = ITexxWindowGuiIntf._RESULTPANEL_SIZE_DEFAULT ;
		}
		if (ph< ITexxWindowGuiIntf._RESULTPANEL_SIZE_MIN){
			ph = ITexxWindowGuiIntf._RESULTPANEL_SIZE_MIN ;
		}
		if (ph> ITexxWindowGuiIntf._RESULTPANEL_SIZE_MAX){
			ph = ITexxWindowGuiIntf._RESULTPANEL_SIZE_MAX ;
		}
		// storing it in the gui object, from where it will be taken 
		// when actually creating the panels
		windowGui.setResultPanelSize(ph) ;
	}
	
	public void retoreMainStatusBarProperties(){
		
		String sv = (String) windowProps.get("statusbar");
		if ((sv!=null) && ( sv.trim().startsWith("0"))){
			windowGui.getMainStatusBar().setVisible(false);
		}else{
			windowGui.getMainStatusBar().setVisible(true);
		}
	}

	private Integer getDefaultX() {
		Integer xpos=600;
		
		Dimension scr = SystemProperties.screenSize() ;
		xpos = scr.width;
		
		return xpos;
	}
	
	
	private Integer getDefaultY() {
		Integer ypos=100;
		
		Dimension scr = SystemProperties.screenSize() ;
		ypos = scr.height;
		
		return ypos;
	}
	private Integer getDefaultW() {
		Integer width=350;
		
		return width;
	}
	private Integer getDefaultH() {
		Integer height=550;
		
		return height;
	}
	
	
	
	public Properties getWindowProps() {
		return windowProps;
	}

	public void setWindowProps(Properties properties) {
		this.windowProps = properties;
	}

	public boolean isFirstStart() {
		// 
		return isFirstStart;
	}
	
	
	
}
